<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  locked,
  resetPassword,
  sysUserPage,
  sysUserRemove,
  unLocked,
} from '#/api/sys/user';
import { Icon } from '#/components/icon';
import { TableAction } from '#/components/table-action';

import DetailForm from './detail.vue';
import UserForm from './form.vue';
import GrantRole from './grant-role.vue';
import { gridSchemas, searchFormSchemas } from './schemas';

const userStore = useUserStore();
const hasTopTableDropDownActions = ref(false);
const userFormRef = ref();
const detailFormRef = ref();
const grantRoleRef = ref();
const gridApiRef = ref();

// 表单配置
const formOptions: VbenFormProps = {
  ...searchFormSchemas,
  collapsed: true,
};

// 表格配置
const gridOptions: VxeGridProps<any> = {
  ...gridSchemas,
  toolbarConfig: {
    ...gridSchemas.toolbarConfig,
    slots: {
      buttons: 'toolbar-buttons',
    },
    custom: {
      icon: 'vxe-icon-menu',
    },
  },
  border: false,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: ({ page }, formValues) => {
        return new Promise((resolve) => {
          sysUserPage({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          }).then(({ records, total }) => {
            resolve({
              total,
              items: records,
            });
          });
        });
      },
    },
  },
};

// 刷新选中状态函数
const refreshCheckboxState = () => {
  hasTopTableDropDownActions.value =
    gridApiRef.value?.grid.getCheckboxRecords().length > 0;
};

// 表格事件
const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    refreshCheckboxState();
  },
  checkboxAll() {
    refreshCheckboxState();
  },
};

// -- 逻辑复用 --
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

onMounted(() => {
  gridApiRef.value = gridApi;
});

// 提取获取选中记录的ID列表
const getSelectedIds = (row?: any) => {
  return row
    ? [row.userId]
    : gridApiRef.value.grid
        .getCheckboxRecords()
        .map((item: any) => item.userId);
};

// 新增用户
const handleAdd = () => {
  userFormRef.value.setData({ isUpdate: false, gridApi });
  userFormRef.value.open();
};

// 编辑用户
const handleEdit = (record: any) => {
  userFormRef.value.setData({ record, isUpdate: true, gridApi });
  userFormRef.value.open();
};

// 用户详情
const handleDetail = (record: any) => {
  detailFormRef.value.setData({ record });
  detailFormRef.value.open();
};

// 授权角色
const handleGrantRole = (record: any) => {
  grantRoleRef.value.setData({ record, gridApi });
  grantRoleRef.value.open();
};

// 重置密码（统一处理）
const handleResetPassword = (row?: any) => {
  const userIds = getSelectedIds(row);
  resetPassword({ userIds }).then(() => {
    message.success('重置密码成功');
    gridApi.reload();
  });
};

// 锁定用户
const handleLocked = (row?: any) => {
  const userIds = getSelectedIds(row);
  locked({ userIds }).then(() => {
    message.success('锁定用户成功');
    gridApi.reload();
  });
};

// 解锁用户
const handleUnLocked = (row?: any) => {
  const userIds = getSelectedIds(row);
  unLocked({ userIds }).then(() => {
    message.success('取消锁定成功');
    gridApi.reload();
  });
};

// 删除用户（统一处理）
const handleDelete = (row?: any) => {
  const userIds = getSelectedIds(row);
  sysUserRemove({ userIds }).then(() => {
    message.success('删除成功');
    gridApi.reload();
  });
};
</script>

<template>
  <Page auto-content-height style="height: 100%">
    <!-- 确保高度生效 -->
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: handleAdd,
            },
          ]"
          :drop-down-actions="[
            {
              label: '重置密码',
              icon: 'ant-design:setting-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '是否重置选中用户密码？',
                confirm: () => handleResetPassword(),
              },
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '确定删除选中用户吗？',
                confirm: () => handleDelete(),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 8px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #toolbar-tools></template>
      <template #ACTION="{ row }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              size: 'small',
              onClick: () => handleDetail(row),
            },
            {
              label: '编辑',
              type: 'link',
              size: 'small',
              onClick: () => handleEdit(row),
            },
          ]"
          :drop-down-actions="[
            {
              label: '重置密码',
              icon: 'ant-design:setting-outlined',
              popConfirm: {
                title: '是否重置该用户密码？',
                confirm: () => handleResetPassword(row),
              },
            },
            {
              label: '授权角色',
              icon: 'ant-design:usergroup-add-outlined',
              onClick: () => handleGrantRole(row),
            },
            {
              label: '锁定用户',
              icon: 'ant-design:lock-outlined',
              popConfirm: {
                title: '是否锁定该用户？',
                confirm: () => handleLocked(row),
              },
              ifShow: () => row.lockFlag === '0',
              disabled: userStore.userInfo?.id === row.userId,
            },
            {
              label: '取消锁定',
              icon: 'ant-design:unlock-outlined',
              popConfirm: {
                title: '是否取消锁定该用户？',
                confirm: () => handleUnLocked(row),
              },
              ifShow: () => row.lockFlag === '9',
              disabled: userStore.userInfo?.id === row.userId,
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              popConfirm: {
                title: '确定删除该用户吗？',
                confirm: () => handleDelete(row),
              },
            },
          ]"
        />
      </template>
    </Grid>
    <UserForm ref="userFormRef" />
    <DetailForm ref="detailFormRef" />
    <GrantRole ref="grantRoleRef" />
  </Page>
</template>
